package cn.zf233.springsecurityjwt.config.upwd;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

/**
 * Created by zf233 on 2021/7/12
 */
@Component("uPwdAuthenticationProvider")
public class UPwdAuthenticationProvider implements AuthenticationProvider {

    @Resource
    private UPwdDetailsService uPwdDetailsService;

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = (String) authentication.getCredentials();
        if (StringUtils.isBlank(username)) {
            throw new UsernameNotFoundException("用户名不可以为空");
        }
        if (StringUtils.isBlank(password)) {
            throw new BadCredentialsException("密码不可以为空");
        }
        UserDetails user = uPwdDetailsService.loadUserByUsername(username);
        if (ObjectUtils.isEmpty(user)) {
            throw new BadCredentialsException("用户信息加载失败");
        }
        if (!passwordEncoder.matches(password, passwordEncoder.encode(user.getPassword()))) {
            throw new BadCredentialsException("密码有误");
        }
        return new UPwdAuthenticationToken(user, password, null);
    }

    @Override
    public boolean supports(Class<?> aClass) {

        return UPwdAuthenticationToken.class.isAssignableFrom(aClass);
    }
}